import { useParams } from "react-router-dom";
import { getQuestionService } from "../services/question";
import { useRequest } from "ahooks";
import { useEffect } from "react";
import { useDispatch } from "react-redux";
import { resetComponents } from "../store/componentsReducer";

function useLoadQuestionData() {
  const { id = "" } = useParams();
  // 定义useRequest的异步函数
  const func = async (id: string) => {
    if (!id) {
      throw new Error("id不存在,没有问卷");
    }
    const data = await getQuestionService(id);
    return data;
  };
  // 使用useRequest调用接口
  const { data, loading, error, run } = useRequest(func, {
    manual: true,
  });
  // 使用useEffect监听变化问卷信息变化，判断id变化来执行加载数据
  useEffect(() => {
    run(id);
  }, [id]);
  // 根据获取的data设置redux
  const dispatch = useDispatch();
  useEffect(() => {
    if (!data) return;
    const { title = "", componentList = [] } = data;
    // 把componentList存储到Redux中
    dispatch(resetComponents({ componentList }));
  }, [data]);

  return { loading, error };
}
export default useLoadQuestionData;
